package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.VerCodeGenerateUtil;
import com.itheima.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/reg")
@Api(tags = "邮箱发送")
public class EmailVerificationController {

    private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);

    @Autowired
    private EmpService empService;

    @Autowired
    private JavaMailSenderImpl mailSender;

    // 发送邮箱验证码
    @GetMapping("/sendEmail")
    @ApiOperation("发送邮箱验证码")
    public Result sendEmail(String email, HttpServletRequest request) {
        if (email == null || !email.matches("^[\\w.-]+@([\\w-]+\\.)+[\\w-]{2,4}$")) {
            return Result.error("请输入有效的邮箱地址");
        }

        HttpSession session = request.getSession();
        String verCode = VerCodeGenerateUtil.getVerCode();
        String time = DateUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss");

        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("code", verCode);
        codeMap.put("email", email);
        session.setAttribute("verCode", codeMap);

        // 5分钟后自动清除验证码
        scheduledExecutorService.schedule(() -> {
            HttpSession s = request.getSession(false);
            if (s != null) {
                Map<String, String> stored = (Map<String, String>) s.getAttribute("verCode");
                if (stored != null && email.equals(stored.get("email"))) {
                    s.removeAttribute("verCode");
                }
            }
        }, 5, TimeUnit.MINUTES);

        // 发送邮件
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("1460420175@qq.com"); // 修改为你的发件邮箱
            helper.setTo(email);
            helper.setSubject("【Share社区】注册验证码");
            helper.setText(buildEmailContent(verCode, time), true);

            mailSender.send(message);
        } catch (MailException e) {
            return Result.error("邮箱地址无效或发送失败");
        } catch (MessagingException e) {
            e.printStackTrace();
            return Result.error("邮件服务异常");
        }

        return Result.success("验证码已发送至 " + email);
    }

    // 用户注册
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String verCode,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Map<String, String> codeMap = (Map<String, String>) session.getAttribute("verCode");

        if (codeMap == null) {
            return Result.error("验证码已过期，请重新获取");
        }

        if (!verCode.toUpperCase().equals(codeMap.get("code")) || !username.equals(codeMap.get("email"))) {
            return Result.error("验证码错误或邮箱不匹配");
        }

        session.removeAttribute("verCode"); // 使用后立即清除

        if (empService.findUserByName(username) != null) {
            return Result.error("该邮箱已被注册");
        }

        int result = empService.addUser(username, password);
        return result == 1 ? Result.success("注册成功") : Result.error("注册失败");
    }

    private String buildEmailContent(String code, String time) {
        return "<h3><span style=\"font-size:16px;\">亲爱的用户：</span></h3>" +
                "<p><span style=\"font-size:14px;\">&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
                "<span style=\"font-size:16px;\">&nbsp;&nbsp;您好！您正在进行邮箱验证，本次请求的验证码为：" +
                "<span style=\"font-size:24px;color:#FFE500;\"> " + code + "</span>，" +
                "本验证码5分钟内有效，请及时完成验证。（请勿泄露）<br>如非本人操作，请忽略该邮件。</span></p>" +
                "<p style=\"text-align:right;\"><span style=\"font-size:16px;\">Share社区</span></p>" +
                "<p style=\"text-align:right;\"><span style=\"font-size:14px;color:#666;\">" + time + "</span></p>";
    }
}